/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Program.js
 * @path:   js-src/album/
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-03-01
 */
qui(
    function (require, exports, module) {
        WrapSys.DynamicDiv = (function () {
            var config = {
                baseDiv: null,
                startMove: false,
                originalRect: null,
                startDrag: false,
                moveParams: null,
                LIMIT_HEIGHT: 600
            }

            var _delayHandler = null;

            function getPos(event) {
                return {
                    x: event.pageX - config.baseDiv.offset().left, y: event.pageY - config.baseDiv.offset().top
                }
            }

            function initDynamicPanel(elementId) {
                config.baseDiv = $("#" + elementId);
                config.baseDiv.delegate("div.jcrop-handle,div.jcrop-dragbar", "mousedown", function (event) {
                    if (!config.startMove) {
                        config.startMove = true;
                        config.moveParams = buildClientPos(event, true);
                        var movePanel = $(event.currentTarget).parent().parent();
                        config.originalRect = getMoveRect(movePanel);
                        $("body").bind("mousemove", moveFunc);
                        $("body").bind("mouseup", mouseUpFunc);
                    }
                })

                config.baseDiv.delegate("div[moveDiv]", "mousedown", function (event) {
                    if (config.startMove) {
                        return;
                    }
                    if (!config.startDrag) {
                        config.startDrag = true;
                        config.moveParams = buildClientPos(event, false);
                        var movePanel = $(event.currentTarget)
                        config.originalRect = getMoveRect(movePanel);
                        config.originalRect.div.bind("mousemove", dragStart);
                        config.originalRect.div.bind("mouseout", dragEnd);
                        config.originalRect.div.bind("mouseup", dragEnd);
                    }
                })
            }

            function doAdjustWidthAuto() {
                if (config.originalRect != null) {
                    $("body").trigger("mouseup");
                    config.originalRect = getMoveRect( config.originalRect.div )
                    var selectedDiv = config.originalRect.div ;
                    var relationImg = selectedDiv.find("img[name=editImg]");
                    var newCss = {x: config.originalRect.x, y: config.originalRect.y,w:0,h:selectedDiv.height()};
                    newCss.w = newCss.h / relationImg[0].naturalHeight * relationImg[0].naturalWidth;
                    if (newCss.w >= config.originalRect.maxWidth) {
                        newCss.w = config.originalRect.maxWidth;
                    }
                    if (newCss.w + newCss.x >= config.originalRect.maxWidth) {
                        newCss.x = config.originalRect.maxWidth - newCss.w;
                    }
                    selectedDiv.css({width: newCss.w, height: newCss.h, left: newCss.x, top: newCss.y })
                    relationImg.css({width: newCss.w, height: newCss.h});
                }
            };
            function doAdjustHeightAuto() {
                if (config.originalRect != null) {
                   $("body").trigger("mouseup");
                    config.originalRect = getMoveRect( config.originalRect.div )
                    var selectedDiv = config.originalRect.div;
                    var relationImg = selectedDiv.find("img[name=editImg]");
                    var newCss = {x: config.originalRect.x, y: config.originalRect.y,h:0,w:selectedDiv.width()};
                    newCss.h = newCss.w / relationImg[0].naturalWidth * relationImg[0].naturalHeight;
                    if (newCss.h >= config.originalRect.maxHeight) {
                        newCss.h = config.originalRect.maxHeight;
                    }
                    if (newCss.h + newCss.y >= config.originalRect.maxHeight) {
                        newCss.y = config.originalRect.maxHeight - newCss.h;
                    }
                    selectedDiv.css({width: newCss.w, height: newCss.h, left: newCss.x, top: newCss.y })
                    relationImg.css({width: newCss.w, height: newCss.h});
                }
            };

            function buildClientPos(event, needDirect) {
                var moveParams = getPos(event);
                if (needDirect) {
                    moveParams.direct = $(event.currentTarget).attr("class").replace(/jcrop-handle/g, "").replace(/jcrop-dragbar/g, "").trim();
                }
                return moveParams
            }

            function getMoveRect(movePanel) {
                console.log(movePanel.attr("id"));
                return {
                    div: movePanel,
                    w: movePanel.width(),
                    h: movePanel.height(),
                    x: movePanel.offset().left - config.baseDiv.offset().left,
                    y: movePanel.offset().top - config.baseDiv.offset().top,
                    maxHeight: config.baseDiv.height(),
                    maxWidth: config.baseDiv.width()
                }
            }


            function moveFunc(event) {
                console.log("event.which" + event.which);
                if (!config.startMove) {
                    console.log("moveFunc false");
                    return;
                }
                if (event.which == 1) {
                    var newPos = getPos(event)
                    var direct = config.moveParams.direct
                    var delta = {x1: config.moveParams.x, x2: newPos.x, y1: config.moveParams.y, y2: newPos.y };
                    updateRect({dlx: delta.x2 - delta.x1, dly: delta.y2 - delta.y1 }, direct)
                }
            }

            function mouseUpFunc() {
                if (config.startMove) {
                    config.startMove = false;
                    $("body").unbind("mousemove", moveFunc);
                    $("body").unbind("mouseup", mouseUpFunc)
                }
            }

            function dragStart(event) {
                console.log("dragStart");
                if (!config.startDrag) {
                    console.log("dragStart false");
                    return
                }
                if (event.which == 1) {
                    var newPos = getPos(event);
                    var delta = {x1: config.moveParams.x, x2: newPos.x, y1: config.moveParams.y, y2: newPos.y };
                    updatePosition({dlx: delta.x2 - delta.x1, dly: delta.y2 - delta.y1 })
                }
            }

            function dragEnd(event) {
                console.log("dragEnd");
                if (config.startDrag) {
                    config.startDrag = false;
                    config.originalRect = getMoveRect(  config.originalRect.div);
                    config.originalRect.div.unbind("mousemove", dragStart);
                    config.originalRect.div.unbind("mouseout", dragEnd);
                    config.originalRect.div.unbind("mouseup", dragEnd);
                }
            }


            function addImg(assignId, imgUrl, elmStyle) {
                if (assignId != null) {
                    buildDynamicDiv(assignId, imgUrl, elmStyle)
                }
            }

            function buildDynamicDiv(elementId, imgUrl, elmStyle) {
                var htmlArr = [];
                var assignSize = null;
                if (elmStyle.w != null) {
                    assignSize = 'rect=' + elmStyle.w + '_' + elmStyle.h;
                }
                if (elmStyle.center == true) {
                    assignSize += ' rectCenter="true" ';
                }
                htmlArr.push('<div moveDiv="true" ' + assignSize + ' id="movePanel_' + elementId + '" style="position: absolute; z-index: 600; display: block; width: 396px; height: 216px;user-select: none;">')
                htmlArr.push(' <img name="editImg" img-id=' + elementId + ' style="position: absolute" onload="WrapSys.DynamicDiv.loadImage(this)" src="' + imgUrl + '">');
                htmlArr.push('<div style="width: 100%; height: 100%; z-index: 310; position: absolute; overflow: hidden;">')
                htmlArr.push('<div class="jcrop-hline" style="position: absolute; opacity: 0.4;"></div>')
                htmlArr.push('<div class="jcrop-hline bottom" style="position: absolute; opacity: 0.4;"></div>')
                htmlArr.push('<div class="jcrop-vline right" style="position: absolute; opacity: 0.4;"></div>')
                htmlArr.push('<div class="jcrop-vline" style="position: absolute; opacity: 0.4;"></div>')
                htmlArr.push('<div class="jcrop-tracker" style="cursor: move; position: absolute; z-index: 360;"></div>')
                htmlArr.push('</div>');
                htmlArr.push('<div zoom-key="true" style="width: 100%; height: 100%; z-index: 320; display: block;">')
                htmlArr.push('<div class="ord-n jcrop-dragbar" style="cursor: n-resize; position: absolute; z-index: 370;"></div>')
                htmlArr.push('<div class="ord-s jcrop-dragbar" style="cursor: s-resize; position: absolute; z-index: 371;"></div>')
                htmlArr.push('<div class="ord-e jcrop-dragbar" style="cursor: e-resize; position: absolute; z-index: 372;"></div>')
                htmlArr.push('<div class="ord-w jcrop-dragbar" style="cursor: w-resize; position: absolute; z-index: 373;"></div>')
                htmlArr.push('<div class="ord-n jcrop-handle"  style="cursor: n-resize; position: absolute; z-index: 374; opacity: 0.5;"></div>')
                htmlArr.push('<div class="ord-s jcrop-handle"  style="cursor: s-resize; position: absolute; z-index: 375; opacity: 0.5;"></div>')
                htmlArr.push('<div class="ord-e jcrop-handle"  style="cursor: e-resize; position: absolute; z-index: 376; opacity: 0.5;"></div>')
                htmlArr.push('<div class="ord-w jcrop-handle"  style="cursor: w-resize; position: absolute; z-index: 377; opacity: 0.5;"></div>')
                htmlArr.push('<div class="ord-nw jcrop-handle" style="cursor: nw-resize; position: absolute; z-index: 378; opacity: 0.5;"></div>')
                htmlArr.push('<div class="ord-ne jcrop-handle" style="cursor: ne-resize; position: absolute; z-index: 379; opacity: 0.5;"></div>')
                htmlArr.push('<div class="ord-se jcrop-handle" style="cursor: se-resize; position: absolute; z-index: 380; opacity: 0.5;"></div>')
                htmlArr.push('<div class="ord-sw jcrop-handle" style="cursor: sw-resize; position: absolute; z-index: 381; opacity: 0.5;"></div>')
                htmlArr.push('</div>')
                htmlArr.push(' <div style="position: absolute;float:right;top:6px;right:6px;z-index:400;cursor:pointer;background-color:brown;color:white" onclick="WrapSys.DynamicDiv.delMaterial(' + elementId + ')">X</div>');
                htmlArr.push('</div>')
                config.baseDiv.append(htmlArr.join(""));
                if (elmStyle != null) {
                    $("#movePanel_" + elementId).css({left: elmStyle.x, top: elmStyle.y})
                }
            }

            function updateRect(delta, direct) {
                console.log("updateRect delta", JSON.stringify(delta));
                var newCss = $.extend(true, {}, config.originalRect);

                if (direct.indexOf("s") != -1) {
                    if (delta.dly >= 0) {
                        newCss.h += delta.dly;
                    } else if (delta.dly + newCss.h >= 0) {
                        newCss.h += delta.dly;
                    } else if (delta.dly + newCss.h + newCss.y >= 0) {
                        newCss.h = -(delta.dly + newCss.h)
                        newCss.y -= newCss.h;
                    } else {
                        newCss.h = newCss.y;
                        newCss.y = 0;
                    }
                } else if (direct.indexOf("n") != -1) {
                    if (delta.dly >= newCss.h) {
                        newCss.y = newCss.y + newCss.h;
                        newCss.h = delta.dly - newCss.y;
                    } else if (delta.dly + newCss.y >= 0) {
                        newCss.y = newCss.y + delta.dly;
                        newCss.h = newCss.h - delta.dly;
                    } else {
                        newCss.h = newCss.y + newCss.h;
                        newCss.y = 0;
                    }

                }
                if (direct.indexOf("e") != -1) {
                    if (delta.dlx >= 0) {
                        newCss.w += delta.dlx;
                    } else if (delta.dlx + newCss.w > 0) {
                        newCss.w += delta.dlx;
                    } else if (delta.dlx + newCss.w + newCss.x >= 0) {
                        newCss.w = -(delta.dlx + newCss.w)
                        newCss.x -= newCss.w;
                        console.log(newCss.w, newCss.x)
                    } else {
                        newCss.w = newCss.x;
                        newCss.x = 0;
                    }
                } else if (direct.indexOf("w") != -1) {
                    if (delta.dlx >= newCss.w) {
                        newCss.x = newCss.x + newCss.w;
                        newCss.w = delta.dlx - newCss.x;
                    } else if (delta.dlx + newCss.x >= 0) {
                        newCss.x = newCss.x + delta.dlx;
                        newCss.w = newCss.w - delta.dlx;
                    } else {
                        newCss.w = newCss.x + newCss.w;
                        newCss.x = 0;
                    }
                }
                if (newCss.y < 0) {
                    newCss.y = 0;
                }
                if (newCss.x < 0) {
                    newCss.x = 0;
                }

                if (newCss.x + newCss.w > newCss.maxWidth) {
                    newCss.w = newCss.maxWidth - newCss.x;
                }
                if (newCss.h + newCss.y >= newCss.maxHeight) {
                    newCss.h = newCss.maxHeight - newCss.y;
                }
                config.originalRect.div.css({width: newCss.w, height: newCss.h, left: newCss.x, top: newCss.y })
                config.originalRect.div.find("img[name=editImg]").css({width: newCss.w, height: newCss.h});
            }

            function updatePosition(delta) {
                var newCss = $.extend(true, {}, config.originalRect);
                newCss.x += delta.dlx;
                newCss.y += delta.dly;
                if (newCss.x < 0) {
                    newCss.x = 0;
                }
                if (newCss.y < 0) {
                    newCss.y = 0;
                }
                if (newCss.h + newCss.y > newCss.maxHeight) {
                    newCss.y = newCss.maxHeight - newCss.h;
                }
                if (newCss.x + newCss.w > newCss.maxWidth) {
                    newCss.x = newCss.maxWidth - newCss.w;
                }
                config.originalRect.div.css({width: newCss.w, height: newCss.h, left: newCss.x, top: newCss.y })
                console.log(JSON.stringify(newCss));
            }

            function loadImage(element) {
                console.log(element.naturalWidth, element.naturalHeight);
                if ($(element).parent().attr("rect") != null) {
                    var rect = $(element).parent().attr("rect").split("_")
                    $(element).css({width: parseInt(rect[0]), height: parseInt(rect[1])})
                    $(element).parent().css({width: parseInt(rect[0]), height: parseInt(rect[1])})
                } else {
                    var rect = { width: element.naturalWidth, height: element.naturalHeight };
                    if (rect.width / rect.height >= $("img[name=panel-bg]").width() / $("img[name=panel-bg]").height()) {
                        if (rect.width >= $("img[name=panel-bg]").width() / 2) {
                            rect.height = element.naturalHeight / element.naturalWidth * $("img[name=panel-bg]").width() / 2;
                            rect.width = $("img[name=panel-bg]").width() / 2;
                        }
                    } else {
                        if (rect.height > $("img[name=panel-bg]").height() / 2) {
                            rect.width = element.naturalWidth / element.naturalHeight * $("img[name=panel-bg]").height() / 2;
                            rect.height = $("img[name=panel-bg]").height() / 2;
                        }
                    }
                    $(element).css(rect)
                    $(element).parent().css(rect)
                }
                if ($(element).parent().attr("rectCenter") != null) {
                    var width = $(element).parent().parent().width();
                    var height = $(element).parent().parent().height();
                    $(element).parent().css({left: (width - $(element).parent().width()) / 2, top: (height - $(element).parent().height()) / 2 })
                }
            }

            function loadBgComplete(event) {
                console.log(event.currentTarget.naturalWidth, event.currentTarget.naturalHeight);
                if (event.currentTarget.naturalHeight > config.LIMIT_HEIGHT) {
                    $(event.currentTarget).css({width: event.currentTarget.naturalWidth / event.currentTarget.naturalHeight * config.LIMIT_HEIGHT, height: config.LIMIT_HEIGHT })
                } else {
                    $(event.currentTarget).css({width: event.currentTarget.naturalWidth, height: event.currentTarget.naturalHeight })
                }
                config.baseDiv.css({width: $(event.currentTarget).width(), height: $(event.currentTarget).height()})
                if (_delayHandler != null) {
                    _delayHandler();
                }

            }

            function loadBg(url, callback) {
                _delayHandler = callback;
                config.baseDiv.find("img[name=panel-bg]").bind("load", loadBgComplete);
                config.baseDiv.find("img[name=panel-bg]").attr("src", url);
            }

            function getConfig() {
                return config;
            }

            function destroy() {
                config.baseDiv.find("div[moveDiv]").remove();
                config.baseDiv.find("img[name=panel-bg]").attr("src", "");
                config.baseDiv.find("img[name=panel-bg]").unbind("load", loadBgComplete);
                _delayHandler = null;
                config.baseDiv.css({width: 1077, height: 608});
                config = {
                    baseDiv: null,
                    startMove: false,
                    originalRect: null,
                    startDrag: false,
                    moveParams: null,
                    LIMIT_HEIGHT: 600
                }
            }

            function delMaterial(elementId) {
                $("#movePanel_" + elementId).remove();
                config.originalRect = null;
            }

            function getMaterials() {
                var moveDivArr = config.baseDiv.find("div[moveDiv]");
                var arrayObj = {};
                var entity = null;
                var bg = config.baseDiv.find("img[name=panel-bg]");
                var ratio = bg[0].naturalHeight / bg.height();
                if (moveDivArr.length > 0) {
                    $.each(moveDivArr, function (i, elemt) {
                        entity = {};
                        entity.id = parseInt($(elemt).attr("id").replace("movePanel_", ""));
                        entity.x = parseInt($(elemt).css("left").replace("px", ""));
                        entity.y = parseInt($(elemt).css("top").replace("px", ""));
                        entity.w = $(elemt).width();
                        entity.h = $(elemt).height();
                        entity.ratio = ratio
                        arrayObj["key_" + entity.id ] = entity
                    })
                }
                return arrayObj
            }

            return {
                initDynamicPanel: initDynamicPanel,
                addImg: addImg,
                loadImage: loadImage,
                loadBg: loadBg,
                getConfig: getConfig,
                destroy: destroy,
                delMaterial: delMaterial,
                getMaterials: getMaterials,
                doAdjustWidthAuto:doAdjustWidthAuto,
                doAdjustHeightAuto:doAdjustHeightAuto
            }
        })()
    }
);